import os, tarfile,shutil
from AnsibleGUI.settings import MEDIA_ROOT,BASE_DIR,ANSIBLE_ROOT

def make_targz(output_filename, source_dir):
    """
    一次性打包目录为tar.gz
    :param output_filename: 压缩文件名
    :param source_dir: 需要打包的目录
    :return: bool
    """
    try:
        with tarfile.open(output_filename, "w:gz") as tar:
            tar.add(source_dir, arcname=os.path.basename(source_dir))

        return True
    except Exception as e:
        print(e)
        return False

def read_gz_file(path):
    if os.path.exists(path):
        with tarfile.open(path, 'r') as pf:
            for line in pf:
                yield line
    else:
        print('the path [{}] is not exist!'.format(path))

def untar(upload_file, module_name):
    """
    解压tar.gz文件
    :param fname: 压缩文件名
    :param dirs: 解压后的存放路径
    :return: bool
    """
    extract_folder = "null"
    extract_path = ANSIBLE_ROOT + 'roles/'
    media = os.path.join(BASE_DIR, MEDIA_ROOT)
    media_file = media + upload_file
    try:
        t = tarfile.open(media_file)
        con = read_gz_file(media_file)
        t.extractall(path = media)
        if getattr(t, '__iter__', None):
            for line in con:
                extract_folder = line.name.split('/')[0]
                break
        target_path = extract_path + module_name
        media_path = media + extract_folder
        if os.path.exists(target_path):
            shutil.rmtree(target_path)
        shutil.move(media_path, target_path)
        return True
    except Exception as e:
        print(e)
        return False